package com.morizhang.merchanmanager.api.monitor.impl;

import com.morizhang.merchanmanager.api.AbstractApiController;
import com.morizhang.merchanmanager.api.dao.AlertDao;
import com.morizhang.merchanmanager.api.dao.CommodityDataDao;
import com.morizhang.merchanmanager.api.dao.CommoditySellingDao;
import com.morizhang.merchanmanager.api.dao.CommodityStorageDao;
import com.morizhang.merchanmanager.api.model.AlertModel;
import com.morizhang.merchanmanager.api.model.CommodityLocationModel;
import com.morizhang.merchanmanager.api.model.CommoditySellingModel;
import com.morizhang.merchanmanager.api.monitor.IMonitor;
import com.morizhang.merchanmanager.api.monitor.MonitorAnnotation;
import com.morizhang.merchanmanager.api.utils.SerialNoGenerator;
import lombok.SneakyThrows;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.List;

@MonitorAnnotation(name = "StockMonitor")
public class StockMonitor implements IMonitor {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractApiController.class);

    @Autowired
    private AlertDao alertDao;

    @Autowired
    private CommoditySellingDao commoditySellingDao;

    @Autowired
    private CommodityStorageDao commodityStorageDao;

    @Autowired
    private CommodityDataDao commodityDataDao;

    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        LOGGER.info("Stock Monitor Called, Checking Stock......");
        List<CommoditySellingModel> allSellingCommodity = commoditySellingDao.selectAllCommoditySelling();
        if (allSellingCommodity == null)
            return;
        for (CommoditySellingModel singleSellingCommodity : allSellingCommodity) {
            int amountPlan = singleSellingCommodity.getAmountPlan();
            if (amountPlan == 0)
                continue;
            String barCode = singleSellingCommodity.getBarCode();
            String shopShelfNo  = singleSellingCommodity.getShopShelfNo();
            CommodityLocationModel commodityLocationQueryParameter = new CommodityLocationModel();
            commodityLocationQueryParameter.setBarCode(barCode);
            commodityLocationQueryParameter.setShopShelfNo(shopShelfNo);
            CommodityLocationModel searchResult = commodityStorageDao.queryCommodityShopLocationByBarcodeShelfNo(commodityLocationQueryParameter);
            if (searchResult.getAmountNow() >= amountPlan)
                continue;
            //触发告警

            //识别商品名称
            String commodityName = commodityDataDao.queryCommodityByBarcode(barCode).getProductName();

            //生成告警识别码
            StringBuilder alertIdentifyCodeBuilder = new StringBuilder();
            alertIdentifyCodeBuilder.append(singleSellingCommodity.getBarCode());
            alertIdentifyCodeBuilder.append('-');
            alertIdentifyCodeBuilder.append(singleSellingCommodity.getShopShelfNo());
            String commodityIdentifyCode = alertIdentifyCodeBuilder.toString();
            alertIdentifyCodeBuilder.append('-');
            alertIdentifyCodeBuilder.append(searchResult.getAmountNow());
            String alertIdentifyCode = alertIdentifyCodeBuilder.toString();

            //判断是否之前已经对该问题进行过告警
            AlertModel alertQueryParameter = new AlertModel();
            alertQueryParameter.setAlertSource(this.getClass().getName());
            alertQueryParameter.setAlertIdentifyCode(alertIdentifyCode);
            AlertModel existAlert = alertDao.selectByIdentifyCode(alertQueryParameter);

            Calendar now = Calendar.getInstance();

            if (existAlert == null) {
                //使用正则判断是否有过期告警，如果有则将其删除
                String REGEXP = commodityIdentifyCode + '-' + "[0-9]";
                alertQueryParameter.setREGEXP(REGEXP);
                List<AlertModel> existExpireAlert = alertDao.selectByIdentifyCodeUsingREGEXP(alertQueryParameter);
                if (existExpireAlert != null && !existExpireAlert.isEmpty()) {
                    for (AlertModel singleExpireAlert : existExpireAlert) {
                        alertDao.deleteAlert(singleExpireAlert.getSerialNo());
                    }
                }

                AlertModel newAlert = new AlertModel();
                newAlert.setSerialNo(SerialNoGenerator.newSerialNo());
                newAlert.setAlertTitle("库存告警-" + commodityName + "-" + singleSellingCommodity.getShopShelfNo());
                newAlert.setAlertSource(this.getClass().getName());
                newAlert.setAlertDetail("在货架 " + singleSellingCommodity.getShopShelfNo() + " 上的商品 " + commodityName + "仅剩余 " + searchResult.getAmountNow() + " 件，请您及时进行处理!");
                newAlert.setAlertIdentifyCode(alertIdentifyCode);
                newAlert.setAlertTime(Long.toString(now.getTimeInMillis()));
                alertDao.addAlert(newAlert);
                continue;
            }

            existAlert.setAlertTime(Long.toString(now.getTimeInMillis()));
            existAlert.setAlertDetail("在货架 " + singleSellingCommodity.getShopShelfNo() + " 上的商品 " + commodityName + "仅剩余 " + searchResult.getAmountNow() + " 件，请您及时进行处理!");
            alertDao.updateAlert(existAlert);
        }
    }
}
